﻿/* ================================================================================
<copyright file="ObserverAppender.cs" company="The Framework Factory, LLC" lastWriteTime="12/05/2012 23:23:47 PM">
  Copyright (c) 2012 The Framework Factory, LLC.  All rights reserved.
</copyright>
=================================================================================== */
using System.Collections.Generic;

using log4net.Appender;
using log4net.Core;

namespace FWF.Logging
{
    /// <summary>
    /// 
    /// </summary>
    public class ObserverAppender : AppenderSkeleton
    {

        private static readonly List<ILoggerListener> _items = new List<ILoggerListener>();

        /// <summary>
        /// Adds the handler.
        /// </summary>
        /// <param name="observer">The observer.</param>
        public static void AddHandler( ILoggerListener observer )
        {
            if ( !_items.Contains( observer ) )
            {
                _items.Add( observer );
            }
        }

        /// <summary>
        /// Removes the handler.
        /// </summary>
        /// <param name="observer">The observer.</param>
        public static void RemoveHandler( ILoggerListener observer )
        {
            if ( _items.Contains( observer ) )
            {
                _items.Remove( observer );
            }
        }

        /// <summary>
        /// This method is called by the <see cref="M:log4net.Appender.AppenderSkeleton.DoAppend(log4net.Core.LoggingEvent)"/> method.
        /// </summary>
        /// <param name="loggingEvent">the event to log</param>
        /// <remarks>Stores the <paramref name="loggingEvent"/> in the events list.</remarks>
        protected override void Append( LoggingEvent loggingEvent )
        {
            LogEventItem itm = LogEventItem.FromLoggingEventData( loggingEvent.GetLoggingEventData() );

            _items.ForEach(
                x => x.Log( itm )
                );
        }

        /// <summary>
        /// Append a bulk array of logging events.
        /// </summary>
        /// <param name="loggingEvents">the array of logging events</param>
        /// <remarks>
        /// 	<para>
        /// This base class implementation calls the <see cref="M:log4net.Appender.AppenderSkeleton.Append(log4net.Core.LoggingEvent)"/>
        /// method for each element in the bulk array.
        /// </para>
        /// 	<para>
        /// A sub class that can better process a bulk array of events should
        /// override this method in addition to <see cref="M:log4net.Appender.AppenderSkeleton.Append(log4net.Core.LoggingEvent)"/>.
        /// </para>
        /// </remarks>
        protected override void Append( LoggingEvent[] loggingEvents )
        {
            for (int i = 0; i < loggingEvents.Length; i++)
            {
                Append( loggingEvents[ i ] );
            }
        }

    }
}